/*
@Time : 2019/12/19 0019 15:59
@Author : visons
*/
package redis

import (
	"fmt"
	"github.com/BurntSushi/toml"
	"github.com/go-redis/redis"
	"log"
	"time"
)

func NewRedisService(path string) *redisService {
	client := &redisService{
		clients: map[string]*redis.Client{},
	}
	client.InitService(path)
	return client
}

type redisService struct {
	clients map[string]*redis.Client
}

func (r *redisService) InitService(path string) {
	conf := map[string]struct {
		//for conn
		Network  string
		Addr     string
		Password string
		DB       int

		DialTimeout  int
		ReadTimeout  int
		WriteTimeout int
		//for pool
		PoolSize int
	}{}

	_, err := toml.DecodeFile(path, &conf)
	if err != nil {
		log.Panicf("read redis service config %s", err)
	}
	fmt.Println(conf)
	for k, v := range conf {
		client := redis.NewClient(&redis.Options{
			Network:      v.Network,
			Addr:         v.Addr,
			Password:     v.Password,
			DB:           v.DB,
			MaxRetries:   1,
			DialTimeout:  time.Duration(v.DialTimeout) * time.Second,
			ReadTimeout:  time.Duration(v.ReadTimeout) * time.Second,
			WriteTimeout: time.Duration(v.WriteTimeout) * time.Second,
			PoolSize:     v.PoolSize,
		})

		val, err := client.Ping().Result()
		if err != nil || val != "PONG" {
			log.Panicf("redis %s %+v init failed", k, v)
		}
		r.clients[k] = client
	}
}

func (r *redisService) GetRedisClient(name string) *redis.Client {
	return r.clients[name]
}

func (r *redisService) Close() {
	for _, c := range r.clients {
		c.Close()
	}
}
